package com.android.dongshouzhi.fragment;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.dongshouzhi.R;
import com.android.dongshouzhi.activity.GoodsDetailActivity;
import com.android.dongshouzhi.adapt.MyDateViewHolder;
import com.android.dongshouzhi.model.auction.AuctionRecentlyOrder;
import com.android.dongshouzhi.model.auction.AuctionRecentlyOrderCallback;
import com.android.dongshouzhi.model.auction.AuctionResultData;
import com.android.dongshouzhi.service.WebSocketService;
import com.android.dongshouzhi.utils.ConstantsUrl;
import com.android.dongshouzhi.utils.HttpUtils;
import com.android.dongshouzhi.utils.MyLog;
import com.android.dongshouzhi.utils.ObjectUtils;
import com.android.dongshouzhi.view.AutoVerticalScrollTextView;
import com.android.dongshouzhi.view.recycleview.CustomLoadMoreView;
import com.android.dongshouzhi.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;


/**
 * 最新成交
 */
public class Fragment2 extends Fragment implements BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.click_resetnetwork_refresh)
    TextView clickResetnetworkRefresh;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;
    private AutoVerticalScrollTextView auction_topline_tv;
    private WebSocketService service;
    private BroadcastReceiver mBroadcastReceiver;
    private AuctionResultData auctionResultData = new AuctionResultData();
    private ArrayList<AuctionRecentlyOrder.DataBean.ListBean> listdata = new ArrayList<>();
    private View view;
    private FragmentActivity mcontext;
    private boolean networkConnected;
    private LayoutInflater inflater;
    private AdaptList adapter;
    private LinearLayoutManager mLayoutManager =  new LinearLayoutManager(mcontext);
    private int page = 1;
    private boolean isRunning = true;
    private View fragment_head;
    private int count_topline=0;
    private String[] auction_toplines = new String[3];





    /**
     * 视图是否已经初初始化
     */
    protected boolean isInit = false;
    protected boolean isLoad = false;
    protected final String TAG = "LazyLoadFragment";
    /**
     * 是否可以加载数据
     * 可以加载数据的条件：
     * 1.视图已经初始化
     * 2.视图对用户可见
     */
    private void isCanLoadData() {
        if (!isInit) {
            return;
        }
        if (getUserVisibleHint()) {
            initData();

            isLoad = true;
            isRunning = true;
            GetDataListData(page);
        } else {
            if (isLoad) {
                isRunning = false;
                service = null;
                getActivity().unregisterReceiver(mBroadcastReceiver);
                mBroadcastReceiver  = null;
                //stopLoad();
            }
        }
    }
    /**
     * 视图销毁的时候讲Fragment是否初始化的状态变为false
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isInit = false;
        isLoad = false;

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        this.inflater = inflater;
        view = inflater.inflate(R.layout.fragment_fragment2, container, false);
        mcontext = getActivity();
        ButterKnife.bind(this, view);
        if (getArguments() != null) {

        }
        isInit = true;
        initUI();
        /**初始化的时候去加载数据**/
        isCanLoadData();
        return view;
    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isCanLoadData();
    }
    public static Fragment2 newInstance() {
        Fragment2 fragment = new Fragment2();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.click_resetnetwork_refresh:
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
                page = 1;
                GetDataListData(page);
                break;
        }
    }

    @Override
    public void onLoadMoreRequested() {
        page = page + 1;
        GetDataListData(page);
    }

    private void initData() {
        GetRecentlyQuery();
        broadcastReceive();
        mRefreshLayout.setColorSchemeResources(R.color.app_title);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                if (networkConnected) {
                    page = 1;
                    GetDataListData(page);
                } else {
                    ObjectUtils.toast(mcontext, "网络连接出现异常");
                    mRefreshLayout.setRefreshing(false);
                }
            }
        });
        //更新拼团快报
        new Thread() {
            @Override
            public void run() {
                while (isRunning) {
                    SystemClock.sleep(3000);
                    handler2.sendEmptyMessage(1);
                }
            }
        }.start();
    }

    private void initUI() {
        fragment_head = inflater.inflate(R.layout.main_fragment2_head_banner, null, false);
        auction_topline_tv = (AutoVerticalScrollTextView)fragment_head.findViewById(R.id.auction_topline_tv);
        adapter = new AdaptList(mcontext, null, "0");
        //  adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.setOnLoadMoreListener(this, mRecyclerView);
        adapter.addHeaderView(fragment_head);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.GetToTop((ImageView) view.findViewById(R.id.top), 1);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                Intent intent = new Intent(mcontext, GoodsDetailActivity.class);
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_SHOW,2);
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_ID,adapter.getItem(position).getId());
                intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TO_DETAIL_COMMON_ID,"");
                startActivity(intent);
            }
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public boolean onItemChildClick(BaseQuickAdapter adapter1, View view, int position) {
                switch (view.getId()) {

                }
                return false;
            }
        });

    }
    /**
     * 处理竞买返回通知消息
     */
    private void DealWithResult()
    {
            /**
             * 有人中拍时
             */
            if(auctionResultData.getMid()>0)
            {
                /**
                 * 头条
                 */
                String keyName = getString(R.string.app_keyname);
                String content = "恭喜" +auctionResultData.getUsername()+"以"
                        +"<font color='#FF0000'>"+"¥"+auctionResultData.getPrice()+"</font>"+ keyName + "到"
                        +"<font color='#99ccff'>"+auctionResultData.getTitle()+"</font>";
                for(int i =0;i<2;i++)
                {
                    auction_toplines[i] = auction_toplines[i+1];
                }
                auction_toplines[2] = content;
            }
    }
    //设置广播监听
    private void broadcastReceive() {
        service = WebSocketService.getInstance();
        // service.sendMsg(get_menus);
        mBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                //更新竞买返回消息
                if(action.equals(WebSocketService.ACTION_NOT)){
                    Intent intents = mcontext.getIntent();
                    auctionResultData = (AuctionResultData)intent.getBundleExtra("bundle").getSerializable("AuctionResult");
                    if(auctionResultData!=null)
                    {

                            DealWithResult();
                    }
                }

            }
        };
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(WebSocketService.ACTION_NOT);

        //注册广播
        mcontext.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }
    /**
     * 获取最新成交消息
     */
    private void GetRecentlyQuery()
    {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address =  ConstantsUrl.domain+ConstantsUrl.ACUTIONRECENTLYORDER;
        MyLog.e("地址", address);
        if (networkConnected) {
            HashMap<String, String> map = new HashMap<>();
            map.put("page","1");
            map.put("size","3");
            HttpUtils.post(address,map, new AuctionRecentlyOrderCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            ObjectUtils.toast(mcontext,e.getMessage());
                        }

                        @Override
                        public void onResponse(AuctionRecentlyOrder response, int id) {

                            if (response.getCode() == 0) {
                                if(response.getData().getList()!=null) {
                                    int size =3;
                                    if(response.getData().getList().size()<3)
                                    {
                                        size = response.getData().getList().size();
                                    }
                                    String keyName = getString(R.string.app_keyname);
                                    for (int i = 0; i < size; i++) {
                                        String content = "恭喜" +response.getData().getList().get(i).getUsername()+"以"
                                                +"<font color='#FF0000'>"+"¥"+response.getData().getList().get(i).getPrice()+"</font>"+ keyName + "到"
                                                +"<font color='#99ccff'>"+response.getData().getList().get(i).getTitle()+"</font>";
                                        auction_toplines[i] = content;
                                    }
                                    if(auction_topline_tv != null){
                                        auction_topline_tv.setText(Html.fromHtml(auction_toplines[0]));
                                    }
                                }
                                else
                                {
                                    for(int i=0;i<3;i++)
                                    {
                                        auction_toplines[i] = "暂无竞买消息";
                                    }
                                }
                            }
                            else
                            {
                                for(int i=0;i<3;i++)
                                {
                                    auction_toplines[i] = "暂无竞买消息";
                                }
                            }
                        }
                    }

            );
        } else {
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }
    /**
     * 商品列表
     */
    private void GetDataListData(final int page) {

        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.ACUTIONRECENTLYORDER ;
        HashMap<String,String> map = new HashMap<>();
        map.put( "page", page+"");
        map.put("size","10");

        if (networkConnected) {

            HttpUtils.get(address, map, new AuctionRecentlyOrderCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    mRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(AuctionRecentlyOrder response, int id) {
                    mRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0) {
                        listdata = new ArrayList<>();
                        MyLog.e("主页列表1", response.getData().getList().get(0).getC_time()+"");
                        if(response.getData().getList()!=null)
                        {
                            mRecyclerView.setLayoutManager(mLayoutManager);
                            for(int i = 0;i<response.getData().getList().size();i++) {
                                listdata.add(new AuctionRecentlyOrder.DataBean.ListBean(AuctionRecentlyOrder.DataBean.ListBean.THREE, response.getData().getList().get(i).getId()
                                        , response.getData().getList().get(i).getC_time(), response.getData().getList().get(i).getThumb()
                                        ,  response.getData().getList().get(i).getPhoto(),response.getData().getList().get(i).getMid(), response.getData().getList().get(i).getPay_time()
                                        , response.getData().getList().get(i).getMarket_price(), response.getData().getList().get(i).getPrice()
                                        , response.getData().getList().get(i).getMid_coin_count(), response.getData().getList().get(i).getUsername()
                                        , response.getData().getList().get(i).getReturns_score(),response.getData().getList().get(i).getMid_count()
                                        ,response.getData().getList().get(i).getSafe_price(),response.getData().getList().get(i).getSafe_rate()
                                        ,response.getData().getList().get(i).getSafe_end(),response.getData().getList().get(i).getTop_price()
                                        ,response.getData().getList().get(i).getTop_end()));
                            }
                            if (page == 1) {
                               adapter.setNewData(listdata);
                                mRecyclerView.setAdapter(adapter);

                            } else {
                                adapter.addData(listdata);
                                adapter.loadMoreComplete();
                            }
                        }
                        else {
                            if(page==1)
                            {
                                noData.setVisibility(View.VISIBLE);
                                noDataTv.setVisibility(View.VISIBLE);
                            }
                            adapter.loadMoreEnd();
                          }
                    } else {
                        noData.setVisibility(View.VISIBLE);
                        noDataTv.setVisibility(View.VISIBLE);
                    }
                }
            });
        } else {

            ObjectUtils.toast(mcontext, "网络未连接");
            adapter.loadMoreFail();
        }
    }
    //更新快报
    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 1:
                    if(auction_topline_tv != null){
                        auction_topline_tv.next();
                        count_topline++;
                        auction_topline_tv.setText(Html.fromHtml(auction_toplines[count_topline%3]));
                    }
                    break;

            }
        }
    };

    public class AdaptList extends BaseMultiItemQuickAdapter<AuctionRecentlyOrder.DataBean.ListBean,MyDateViewHolder> {
        private String type;
        private FragmentActivity mcontext;
        private int limitposition;

        public List<AuctionRecentlyOrder.DataBean.ListBean> data;
        public AdaptList(FragmentActivity context, List<AuctionRecentlyOrder.DataBean.ListBean> data, String type) {
            super(data);
            this.data=data;
            this.mcontext = context;
            this.type = type;
            addItemType(AuctionRecentlyOrder.DataBean.ListBean.THREE, R.layout.item_ry_aishang_fragment2);
        }



        @Override
        protected void convert(MyDateViewHolder holder, AuctionRecentlyOrder.DataBean.ListBean  mineChoujiangdata) {
            switch (holder.getItemViewType()) {
                case AuctionRecentlyOrder.DataBean.ListBean.THREE:
                    if(Float.parseFloat(mineChoujiangdata.getPrice())>=Float.parseFloat(mineChoujiangdata.getSafe_price())) {
                        holder.setVisible(R.id.turnover_ll,true);
                        holder.setVisible(R.id.safeprice_ll,false);
                        ImageView v = (ImageView) holder.getView(R.id.item_list_mine_dingdang_img2);
                        ObjectUtils.photo2(mContext, mineChoujiangdata.getThumb(), v);
                        int c_time = Integer.parseInt(mineChoujiangdata.getC_time());
                        long msl = (long) c_time * 1000;
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String text = format.format(msl);
                        ((TextView) holder.getView(R.id.turnover_time)).setText(text);
                        ((TextView) holder.getView(R.id.marking_price2)).setText(mineChoujiangdata.getMarket_price());
                        ((TextView) holder.getView(R.id.turnover_price)).setText(mineChoujiangdata.getPrice());
                        ((TextView) holder.getView(R.id.turnover_people)).setText(mineChoujiangdata.getUsername());
                        float percent = (Float.parseFloat(mineChoujiangdata.getPrice()) / Float.parseFloat(mineChoujiangdata.getMarket_price()))*100;
                        float savepercent = 100 - percent;
                        DecimalFormat df = new DecimalFormat(".00");
                        String aishang_savepercent = df.format(savepercent);
                        holder.setText(R.id.save_percent, aishang_savepercent + "%");
                    }else
                    {
                        ImageView v = (ImageView) holder.getView(R.id.item_list_mine_dingdang_img1);
                        ObjectUtils.photo2(mContext, mineChoujiangdata.getThumb(), v);
                        int c_time = Integer.parseInt(mineChoujiangdata.getC_time());
                        long msl = (long) c_time * 1000;
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String text = format.format(msl);
                        ((TextView) holder.getView(R.id.turnover_time)).setText(text);
                        holder.setVisible(R.id.turnover_ll,false);
                        holder.setVisible(R.id.safeprice_ll,true);
                    }
                    break;

            }
        }

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}